package com.kung.qvs.ui.main.fragment;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.SupplierBean;
import com.kung.qvs.entity.database.SqlManager;
import com.kung.qvs.utils.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class SupplierEditViewModel extends BaseViewModel<JtRepository> {
    public SupplierEditViewModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  //设置日期格式

    public ObservableField<String> mSupplierName = new ObservableField<>("");    //产地
    public ObservableField<String> mSupplierCode = new ObservableField<>("");    //编号
    public ObservableField<String> mAddress = new ObservableField<>("");    //联系地址
    public ObservableField<String> mContact = new ObservableField<>("");    //联系方式
    public ObservableField<String> mPhone = new ObservableField<>("");    //电话

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent eventToBackPage = new SingleLiveEvent<>();
    }

    public BindingCommand onCommandBack = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToBackPage.call();
        }
    });

    public BindingCommand onCommandSave = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (StringUtils.isTrimEmpty(mSupplierName.get())) {
                ToastUtils.showShort("请输入供应商名称");
                return;
            }

            SupplierBean bean = new SupplierBean();
            bean.set_id(null);
            bean.setSupplierName(mSupplierName.get());
            bean.setSupplierCode(mSupplierCode.get());
            bean.setContact(mContact.get());
            bean.setPhone(mPhone.get());
            bean.setAddress(mAddress.get());
            bean.setFcodeT(DateUtils.getCurrentTime());
            bean.setFcdate(df.format(new Date()));

            if(SqlManager.insertOrReplaceSupplierBean(bean) > 0 ){
                //刷新页面二维码
                ToastUtils.showShort("保存成功");
                //关闭页面
                uc.eventToBackPage.call();
            }
        }
    });
}
